import store from '@/store/index.js'
import Mock from 'mockjs'
import {
  v4 as uuidv4
} from 'uuid'
import shortid from 'shortid'

/**
 * 微信登录
 */
function loginByWechat() {
  return new Promise((resolve, reject) => {
    try {
      uni.login({
        provider: 'weixin', //使用微信登录
        success: async (res) => {
          let code = res.code
          console.log(res.code);
          let wechat_res = await getWechatInfo(code)
          let {
            openid
          } = wechat_res.result.data
          await setUser(openid)
          return resolve()
        }
      });
    } catch (err) {
      return reject(err)
    }
  })
}

async function getWechatInfo(code) {
  return await uniCloud.callFunction({
    name: "wxlogin",
    data: {
      code
    }
  })
}

async function setUser(openid_mp) {
  let find_user_res = await uniCloud.callFunction({
    name: "star-community-user",
    data: {
      flag: 3,
      data: {
        openid_mp
      }
    }
  })

  console.log(find_user_res);

  let vuex_user = null

  if (find_user_res.result.data.length > 0) {
    vuex_user = find_user_res.result.data[0]
  } else {
    vuex_user = {
      id: uuidv4().replace(/-/g, ''),
      isAdmin: false,
      openid_mp,
      avatar: Mock.Random.image('50x50', Mock.Random.color(), 'avatar'),
      nickname: shortid.generate(),
      introduction: '',
      gender: -1,
      backgroundImg: '',
      careCount: 0,
      fansCount: 0,
      likeCount: 0,
      collectCount: 0
    }
    let add_user_res = await uniCloud.callFunction({
      name: "star-community-user",
      data: {
        flag: 1,
        data: {
          ...vuex_user
        }
      }
    })
    console.log(add_user_res);
  }
  if (vuex_user) {
    // 保存到vuex
    store.commit('$uStore', {
      name: 'vuex_user',
      value: vuex_user
    })
  }
}

export default loginByWechat;